using System.Collections.Generic;
using System.Linq;

namespace InstantMessenger.Transports
{
    public class DesktopTransport : ITransport
    {
        private readonly List<Contact> contacts = new List<Contact>();
        private readonly IDictionary<string, MessageForm> messageFormsMap = new Dictionary<string, MessageForm>();

        public string DisplayName { get { return "Desktop"; } }

        public void Start(IEnumerable<Contact> allContacts)
        {
            contacts.AddRange(allContacts.ToList());
        }

        public void Stop()
        {
        }

        public bool DeliverMessage(string sender, string recipient, string message)
        {
            messageFormsMap[recipient].ReceiveMessage(sender, message);
            return true;
        }

        public bool IsOnline(Contact contact)
        {
            return true;
        }

        public void AddContact(Contact contact)
        {
            var messageForm = new MessageForm(contact);
            messageFormsMap.Add(contact.Name, messageForm);
            messageForm.Show();
        }

        public void RemoveContact(Contact contact)
        {
            var messageForm = messageFormsMap[contact.Name];
            if (!messageForm.IsDisposed)
                messageForm.TransportEnded();
            messageFormsMap.Remove(contact.Name);
        }
    }
}